cells = [0]*40
cells[30] = 1
i = 25


def put():
	assert not (cells[i] & 2)
	cells[i] |= 2
def pick():
	assert cells[i] & 2
	cells[i] &= ~2
def left():
	global i
	i-=1
def right():
	global i
	i+=1
def wave():
	assert cells[i] & 1
	return True

def drawstate(f):
	x=''.join('$' if c & 1 else 
		('!' if c & 2 else '.') 
		for c in cells)
	print '%16s: %s' % (f,x)
	print ' '*18+ ' '*i + '^'

#=======================================
# THE STATE MACHINE
#=======================================
def A(s):
	if s == '10':
		return wave, A
	if s == '01':
		return right, B
	if s == '00':
		return put, A

def B(s):
	if s == '10':
		return wave, B
	if s == '00':
		return put, B
	if s == '01':
		return left, C

def C(s):
	if s == '10':
		return wave, C
	if s == '00':
		return left, C
	if s == '01':
		return pick, D

def D(s):
	if s == '00':
		return left, E

def E(s):
	if s == '10':
		return wave, E
	if s == '00':
		return put, E
	if s == '01':
		return right, F

def F(s):
	if s == '10':
		return wave, F
	if s == '00':
		return right, F
	if s == '01':
		return pick, G

def G(s):
	if s == '00':
		return right, B


#=======================================

success=False
drawstate('init->A')
next = A
while not success:
	tr = '1' if cells[i] & 1 else '0'
	fl = '1' if cells[i] & 2 else '0'
	curr = next
	cmd, next = curr(tr+fl)
	success=cmd()
	drawstate('%s:%s->%s' % (curr.__name__, cmd.__name__, next.__name__))






